package com.iweibo.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 数据库操作基类,主要用于:<br>
 * 1.创建表;<br>
 * 2.更新表;<br>
 * @author nibo
 * @date 2012-10-15
 *
 */
public class DatabaseHelper extends SQLiteOpenHelper {
	private static final String TAG = "DatabaseHelper";

	public DatabaseHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	public DatabaseHelper(Context context) {
		super(context, DBConfig.DB.DB_NAME, null, DBConfig.DB.DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(TAG, "创建数据库...");
		Log.i(TAG, "创建表:" + DBConfig.Table.USER_INFO_NAME);
		db.execSQL(DBConfig.Table.USER_INFO_CREATE);
		Log.i(TAG, "创建数据库成功...");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, "数据库更新,删除数据库...");
		Log.i(TAG, "删除数据表:" + DBConfig.Table.USER_INFO_NAME);
		db.execSQL(DBConfig.Table.USER_INFO_DROP);
		Log.i(TAG, "数据库删除成功...");
		onCreate(db);
	}
	
	/**
	 * 关闭数据库连接,释放资源
	 * @param database 数据库操作对象
	 */
	public static void close(SQLiteDatabase database) {
		if (null != database && database.isOpen()) {
			database.close();
		}
	}
	
	/**
	 * 关闭数据库连接,释放资源
	 * @param cursor 数据库游标对象
	 * @param database 数据库操作对象
	 */
	public static void close(Cursor cursor, SQLiteDatabase database) {
		if (null != cursor && !cursor.isClosed()) {
			cursor.close();
		}
		close(database);
	}

}
